import { md5 } from '@/lib/md5';
/*检验参数中是否包含html标签*/
export const checkHtml = (htmlStr) => {
  var reg = /<[^>]+>/g;
  return reg.test(htmlStr);
}

//签名特殊字符转换
export const TransferString = (content) => {
  let string = content;
  try {
    string = string.replace(/\r\n/g, '\\N')
      .replace(/\n/g, '\\N')
      .replace(/\t/g, '\\T');
  } catch (e) {
    uni.$u.toast(e.message);
  }
  return string;
}

/**
 * paramsFormat 公共参数添加
 * params 接口所需参数
 * 向接请参数中统一添加  member_id，account_type，token，timestamp 时间戳，device_platform设备平台
 */
export const paramsFormat = (params, addParams, url) => {
  var isjson = typeof (params) == 'object' && Object.prototype.toString.call(params).toLowerCase() == '[object object]' && !params.length;

  if (isjson) {
    var np = Object.assign(addParams, params);
    var newobj = {}; //把参数中的空值过滤
    for (var key in np) {
      if ((np[key] && typeof (np[key]) != 'undefined') || np[key] == 0) {
        if ((typeof (np[key]) == 'string') && np[key].length <= 0) {
          continue;
        } else {
          newobj[key] = np[key];
        }
      }
    }
    var newkey = Object.keys(newobj).sort(); //对参数根据key按照ASCll码从小到大排序
    var newparam = {};
    var paramStr = '';
    let checkParamsStr = ''
    const skipCheckList = ['versions', 'network', 'wxVersions', 'deviceBrand', 'osVersion', 'sdkVersion', 'deviceType', 'deviceId', 'device_brand', 'device_id', 'device_platform']
    for (var i = 0; i < newkey.length; i++) { //向新创建的对象中按照排好的顺序依次增加键值对
      if (newobj[newkey[i]] instanceof Object) {
        if (skipCheckList.indexOf(newkey[i]) == -1) {
          checkParamsStr += newkey[i] + '=' + JSON.stringify(newobj[newkey[i]]) + '&';
        }
        paramStr += newkey[i] + '=' + JSON.stringify(newobj[newkey[i]]) + '&';
      } else {
        if (skipCheckList.indexOf(newkey[i]) == -1) {
          checkParamsStr += newkey[i] + '=' + newobj[newkey[i]] + '&';
        }
        paramStr += newkey[i] + '=' + newobj[newkey[i]] + '&';
      }
      newparam[newkey[i]] = newobj[newkey[i]];
    }
    /* uni.showModal({
      title: 'html检查',
      content: paramStr,
    });*/
    if (checkHtml(checkParamsStr) && url.indexOf('addCustomerBulletin') == -1 && url.indexOf('updateCustomerBulletin') == -1) {
      uni.$u.toast('参数中包含非法字符', {
        icon: '',
        time: 3
      });
      return false;
    }

    paramStr += 'secret=xfs7Alc74oCVpHXg97etTs';
    paramStr = paramStr.toUpperCase();
    paramStr = TransferString(paramStr);
    var lastparam = Object.assign({}, np);
    lastparam.sign = md5(paramStr);
    return lastparam;
  } else {
    return params;
  }
}
